package com.ugoodtech.mdcc.core.service.impl;

/* Copyright (C) Ugoodtech, Inc - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 */

import com.ugoodtech.mdcc.core.service.ResourceService;
import com.ugoodtech.mdcc.core.domain.Resource;
import com.ugoodtech.mdcc.core.repository.ResourceRepository;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class ResourceServiceImpl implements ResourceService {
    private ResourceRepository resourceRepository;
    //    @Value("${photos.basedir}")
    private String basePath;

    @Override
    public Resource save(String filename, byte[] bytes) throws IOException {
        //decide the attachment's path
        String suffixPath = this.getSuffixPath();
        Path dir = Paths.get(basePath, suffixPath);
        if (!Files.exists(dir)) {
            try {
                Files.createDirectories(dir);
            } catch (FileAlreadyExistsException x) {
                //
            }
        }

        Path filePath = Paths.get(basePath, suffixPath, filename);
        Random rand = new Random();
        String randomName = filename;
        while (Files.exists(filePath)) {
            int randomNum = rand.nextInt();
            randomName = randomName + "_" + Math.abs(randomNum);
            filePath = Paths.get(basePath, suffixPath, randomName);
        }
        //
        Files.write(filePath, bytes, StandardOpenOption.CREATE);
        Resource attachment = new Resource();
        attachment.setName(filename);
        attachment.setMimeType(Files.probeContentType(filePath));
        attachment.setPath(suffixPath + File.separator + randomName);
        attachment.setCreationTime(new Date());
        this.resourceRepository.save(attachment);
        return attachment;
    }

    @Override
    public void delete(Long resourceId) {
        Resource attachment = this.resourceRepository.findOne(resourceId);
        attachment.setDeleted(true);
        this.resourceRepository.save(attachment);
    }

    @Override
    public void readResourceBody(Long attachmentId, OutputStream os) throws IOException {
        Resource attachment = this.resourceRepository.findOne(attachmentId);
        Path path = Paths.get(basePath, attachment.getPath());
        InputStream inputStream = Files.newInputStream(path);
        IOUtils.copy(inputStream, os);
        inputStream.close();
    }

    private String getSuffixPath() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
        return format.format(new Date());
    }
}
